import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse, type InternalAxiosRequestConfig } from "axios";

import { ElMessage } from 'element-plus';


const config = {
    // 接口请求的根地址
    // baseURL: 'http://localhost:8080',
    baseURL: '/api',
    timeout: 10000,

};


// 接口返回值类型
export interface Result<T = any> {
    code: number,
    msg: string,
    data: T,
}



class Http {
    private instance: AxiosInstance;

    constructor(config: AxiosRequestConfig) {
        this.instance = axios.create(config);
        // 拦截器
        this.interceptors();





    }
    private interceptors() {
        this.instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
            let token = '';
            if (token && config) {
                config.headers!['token'] = token;
            }

            return config;

        }, (error: any) => {
            error.data = {};
            error.data.msg = '服务异常请联系管理员'
            return error;
        });



        this.instance.interceptors.response.use((res: AxiosResponse) => {
            if (200 == res.data.code) {
                return res.data
            } else {
                ElMessage.error(res.data.msg || '服务请求异常');
                return Promise.reject(res.data.msg || '服务请求异常');
            }
        }, (error) => {
            error.data = {};
            if (error && error.response) {
                switch (error.response.status) {
                    case 401:
                        error.data.msg = '请重新登录';
                        ElMessage.error(error.data.msg);
                        break;

                    case 404:
                        error.data.msg = '接口不存在';
                        ElMessage.error(error.data.msg);
                        break;






                }

            } else {
                error.data.msg = "连接服务器失败";
                ElMessage.error(error.data.msg);
            }

            return Promise.reject(error);


        });

    }


    post<T = Result>(url: string, data?: object): Promise<T> {
        return this.instance.post(url, data);
    }

    put<T = Result>(url: string, data?: object): Promise<T> {
        return this.instance.put(url, data);
    }

    get<T = Result>(url: string, params?: object): Promise<T> {
        return this.instance.get(url, { params });
    }

    delete<T = Result>(url: string): Promise<T> {
        return this.instance.delete(url);
    }



    upload<T = Result>(url: string, params?: object): Promise<T> {
        return this.instance.post(url, params, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        });
    }
}



export default new Http(config)









